package ntd.util.frame.action.database;

import cn.hutool.core.lang.Opt;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import cn.hutool.db.sql.Order;
import cn.hutool.json.JSONUtil;
import com.c.opt.ComOpt;
import com.c.opt.query.ComOptQueryWrapper;
import com.c.opt.query.ComQueryInfo;
import com.ToolOpt;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.config.common.bo.PageBO;
import ntd.util.frame.action.ActionPage;
import ntd.util.frame.action.database.enums.EnumDataLevel;
import ntd.util.frame.action.database.factory.FactoryTableBuild;


public class ActionTablePage extends ActionAbs {

    @Override
    public ActionInfo info() {
        return new ActionInfo("数据-查询-分页", "action-table-page", new ActionTablePage());
    }

    @Override
    public ActionOutBo handle() {
        
        ComOpt<Object> comOpt = ToolOpt.get(actionInBo.getDataCode(), actionInBo.dsId());

        ComOptQueryWrapper queryWrapper = new ComOptQueryWrapper(actionInBo.getDataCode(), ComQueryInfo.transform(actionInBo.getParamStr("rules")));

        // 数据权限过滤
        Opt.ofBlankAble(actionInBo.getParamStr("dataLevel")).ifPresent(s -> queryWrapper.dataLevel(EnumDataLevel.valueOf(s)));

        // 私有筛选包装
        Opt.ofEmptyAble(FactoryTableBuild.build(actionInBo.getDataCode())).ifPresent(comQueryInfos -> {
            comQueryInfos.forEach(queryWrapper::build);
        });

        Opt.ofBlankAble(actionInBo.getParamStr("sorts")).ifPresent(str -> {
            if (JSONUtil.isTypeJSONArray(str)) {
                JSONUtil.toList(str, Order.class).forEach(queryWrapper::order);
            }
        });

        Page page = ActionPage.page(actionInBo);

        PageResult<Entity> pageResult = comOpt.page(queryWrapper, page.getPageNumber(), page.getPageSize());

        return new ActionOutBo(new PageBO<>(pageResult, pageResult.getTotal()));
    }

}
